//   meanfilter.cpp - impelementation of 
//   1D and 2D mean filter routines
//
//   The code is property of LIBROW
//   You can use it on your own
//   When utilizing credit LIBROW site
#include "stdafx.h"
#include <memory.h>
#include "meanfilter.h"

//   1D MEAN FILTER implementation
//     signal - input signal
//     result - output signal
//     N      - length of the signal
static void _meanfilter(const element* signal, elementOut* result, int N, int ker)
{
	// 0 1 2 3 4 5 6 7 ker=3
	int ker2 = ker / 2;
	//   Move window through all elements of the signal
	for (int i = ker2; i < N - ker2 - 1 ; ++i){
		double sum = 0;
		for (int k = -ker2; k <= ker2; k++){
			sum += signal[i + k];
		}
		result[i - ker2] = sum / (ker2 + ker2 + 1);
	}
}

//   1D MEAN FILTER wrapper
//     signal - input signal
//     result - output signal
//     N      - length of the signal
void meanfilter(element* signal, elementOut* result, int N, int ker)
{
	if (ker % 2 == 0){
		ker++;
	}
	int ker2 = ker / 2;
	//   Check arguments
	if (!signal || N < 1)
		return;
	//   Treat special case N = 1
	if (N == 1)
	{
		if (result)
			result[0] = signal[0];
		return;
	}
	//   Allocate memory for signal extension
	element* extension = new element[N + 2 * ker2];
	//   Check memory allocation
	if (!extension)
		return;
	//   Create signal extension
	memcpy(extension + ker2, signal, N * sizeof(element));

	for (int i = 0; i < ker2; i++){
		extension[i] = signal[ker2 - i - 1];
		extension[N + i + ker2] = signal[N - i - 1];
	}

	//   Call mean filter implementation
	_meanfilter(extension, result, N + ker, ker);
	//   Free memory
	delete[] extension;
}

